package cn.lijigou.shopping;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import cn.lijigou.shopping.alipay.Alipay;
import cn.lijigou.shopping.domain.MRsa;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.service.ServerService;
import cn.lijigou.shopping.util.GetSingleThreadPool;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ConfirmOrderActivity extends MActivity implements OnClickListener, OnTouchListener{
	
	private TextView mTotalPrice = null;
	private TextView mShop_title = null;
	private TextView mPhoneNum = null;
	private TextView mReceiver = null;
	private TextView mAddress = null;
	private TextView mMsg = null;
	private Shop shop;
//	private Button mBankCard;
//	private Button mAlipay;
	private TextView mTitleLeft;
	private LinearLayout titleLeftView;
	private TextView mTitleRight;
	private TextView mTitleCenter;
	private TextView mShowNum;
	private TextView mCoupon;
	private Button mButton_pay;
	private String totalprice;
	private String mCouponCode = "";
	private Boolean visible;
	public static Dialog mDialog;
	public  Button mBankCard;
	public  Button mAlipay;
	public  ProgressBar mProgressBar;
	private Boolean isFlower;
	private  MRsa mRsa = null;
	private ProgressDialog mProgress = null;
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler alipayHandler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what ==1){
				Alipay alipay = new Alipay(ConfirmOrderActivity.this, shop.getId(), OrderApprobateActivity.o_size, OrderApprobateActivity.mobile,shop.getTitle(),
	        			OrderApprobateActivity.receiver_name,OrderApprobateActivity.receiver_address,OrderApprobateActivity.leave_msg, mCouponCode);
	        	alipay.alipay();
	        	
			}else if(msg.what == 10){
				hideProgress();
				Intent mIntent = new Intent(ConfirmOrderActivity.this, CompleteOrderActivity.class);
				mIntent.putExtra("shopTitle", shop.getTitle());   
				ConfirmOrderActivity.this.startActivity(mIntent);
			}
		};
	};
	
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.confirm_order);
		overridePendingTransition(R.anim.push_in,R.anim.push_out);
		
		shop = (Shop)this.getIntent().getSerializableExtra("shop");
		totalprice = this.getIntent().getStringExtra("mTotalprice");
		mCouponCode = this.getIntent().getStringExtra("mCouponCodeMoney");
		isFlower = this.getIntent().hasExtra("flower");
		
		mTitleLeft = (TextView)this.findViewById(R.id.title_btn_left);
		titleLeftView = (LinearLayout)this.findViewById(R.id.titleLeftView);
		mTitleLeft.setBackgroundResource(R.drawable.title_back_normal);
		
		mTitleRight = (TextView)this.findViewById(R.id.title_btn_right);
		mTitleRight.setVisibility(View.GONE);
		mTitleCenter = (TextView)this.findViewById(R.id.text_center);
		mTitleCenter.setText("确认订单");
		findViewById(R.id.titleRightView).setVisibility(View.GONE);
		
		mShop_title = (TextView) this.findViewById(R.id.confirm_shop_title);
		mTotalPrice = (TextView) this.findViewById(R.id.confirm_total_price);
		mPhoneNum = (TextView) this.findViewById(R.id.confirm_mobile);
		mReceiver = (TextView) this.findViewById(R.id.confirm_name);
		mAddress = (TextView) this.findViewById(R.id.confirm_address);
		mMsg = (TextView) this.findViewById(R.id.confirm_message);
		mShowNum = (TextView)this.findViewById(R.id.confirm_alert);
		mCoupon = (TextView)this.findViewById(R.id.confirm_coupon);
		mButton_pay = (Button)this.findViewById(R.id.button_pay);
		
		if("0".equals(totalprice) || "0.0".equals(totalprice) || "0.00".equals(totalprice)){
			mButton_pay.setText("确定");
		}
		if(shop != null){
			mShop_title.setText(shop.getTitle());
		}
		
		mTotalPrice.setText(totalprice);
		if(mCouponCode !=null && mCouponCode.equals("0")){
			mCoupon.setText("未使用");
		}else{
			mCoupon.setText(mCouponCode);
		}
		
		if(isFlower){
			this.findViewById(R.id.confirm_layout_address).setVisibility(View.VISIBLE);
			this.findViewById(R.id.confirm_layout_name).setVisibility(View.VISIBLE);
		}
		
		
		mPhoneNum.setText(OrderApprobateActivity.mobile);
		mReceiver.setText(OrderApprobateActivity.receiver_name);
		mAddress.setText(OrderApprobateActivity.receiver_address);
		mMsg.setText(OrderApprobateActivity.leave_msg);
		mShowNum.setText(Html.fromHtml("*您将通过支付宝安全购买团购，10分钟之内团购短信将会发送到手机号："
				+"<font color=#e47702>"+OrderApprobateActivity.mobile+"</font> "
				+"<br>"+"*"+
				+shop.getBuy_end_time() + ":00-" + shop.getBuy_start_time() + ":00间的订单，我们将在第二天工作时间帮您处理")
				);
		setOnClickListeners();
		ShopDetailActivity.mList.add(this);
		
		OrderApprobateActivity.button_next.setEnabled(true);
		
	}
	
	
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	private void  setOnClickListeners(){
		titleLeftView.setOnClickListener(this);
		mButton_pay.setOnClickListener(this);
		mButton_pay.setOnTouchListener(this);
		
	}
	
	public void onClick(View v) {
		MSystem.pv +=1;
		switch (v.getId()) {
		case R.id.button_pay:
			MSystem.buy +=1;
			mButton_pay.setEnabled(false);
			showPayDialog();
			
			
			break;
		case R.id.alipay:
			alipayHandler.sendEmptyMessage(1);
        	
			break;
		case R.id.titleLeftView:
			if(ShopDetailActivity.mList.contains(this)){
				ShopDetailActivity.mList.remove(this);
			}
			this.finish();
			break;
		 
		}
	}
	
	
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub\
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if(v.getId() == mButton_pay.getId()){
				mButton_pay.setTextColor(Color.WHITE);
				mButton_pay.setBackgroundResource(R.drawable.security_alipay_pressed);
			}
			
			break;
		case MotionEvent.ACTION_UP:
			if(v.getId() == mButton_pay.getId()){
				mButton_pay.setTextColor(Color.BLACK);
				mButton_pay.setBackgroundResource(R.drawable.security_alipay_normal);
			}
			break;

		default:
			break;
		}

		return false;
	}
	
	private void showPayDialog() {
		if("0".equals(totalprice) || "0.0".equals(totalprice) || "0.00".equals(totalprice)){
			executorService.execute(new Thread() {
				public void run() {
					showProgress();
					if (mRsa == null) {
						mRsa = ServerService.first_pay(MSystem.uid, MSystem.session, shop.getId(), OrderApprobateActivity.o_size,
								OrderApprobateActivity.mobile, OrderApprobateActivity.receiver_name,
								OrderApprobateActivity.receiver_address, OrderApprobateActivity.leave_msg, mCouponCode);
					}
					if (mRsa != null) {
						// 保存虚拟账号
						SharedPreferences sp = activity.getSharedPreferences("user", Context.MODE_PRIVATE);
						Editor edit = sp.edit();
						edit.putString("uid", mRsa.getUser_id());
						edit.putString("session", mRsa.getSession());
						edit.putString("isTmp", mRsa.getIsTmp());
						edit.commit();
						String info = mRsa.getInfo();
						alipayHandler.sendEmptyMessage(10);
					} else {
						hideProgress();
						Toast.makeText(ConfirmOrderActivity.this, "购买失败，请重试", 1).show();
					}

				};
			});
			mButton_pay.setEnabled(true);
		}else{
			// TODO Auto-generated method stub
			LayoutInflater factory=LayoutInflater.from(ConfirmOrderActivity.this);
			final View v1=factory.inflate(R.layout.choose_pay_method,null);
			mDialog = new Dialog(ConfirmOrderActivity.this,android.R.style.Theme_Translucent_NoTitleBar);
			mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
	                WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			mDialog.setContentView(v1);
	 
			mProgressBar = ((ProgressBar) mDialog.findViewById(R.id.progressBar_wait));
			mBankCard = ((Button) mDialog.findViewById(R.id.bank_card));
			mBankCard.setOnClickListener(new OnClickListener() {

						
						public void onClick(View v) {
							
							// write your code to do things after users clicks CANCEL
							
							mBankCard.setEnabled(false);
							mProgressBar.setVisibility(View.VISIBLE);
							mDialog.setContentView(v1);
	    	            	Alipay alipay_bank = new Alipay(ConfirmOrderActivity.this, shop.getId(), OrderApprobateActivity.o_size, OrderApprobateActivity.mobile,
	    	            			shop.getTitle(),OrderApprobateActivity.receiver_name,
	    	            			OrderApprobateActivity.receiver_address,OrderApprobateActivity.leave_msg, mCouponCode);
	    	            	alipay_bank.alipayCard();
	    	            	mDialog.dismiss();
	    	            	mButton_pay.setEnabled(true);
						}
					});
			mAlipay = ((Button) mDialog.findViewById(R.id.alipay));
			mAlipay.setOnClickListener(new OnClickListener() {

						
						public void onClick(View v) {
							// write your code to do things after users clicks OK
							//在订单详情--商品详情下单时改变Orders.isRefresh的值为true，实现去网络端重新更新订单
							mAlipay.setEnabled(false);
							mProgressBar.setVisibility(View.VISIBLE);
							mDialog.setContentView(v1);
							alipayHandler.sendEmptyMessage(1);
							
//	    	            	Alipay alipay = new Alipay(ConfirmOrderActivity.this, shop.getId(), OrderApprobateActivity.o_size, OrderApprobateActivity.mobile,
//	    	            			shop.getTitle(),OrderApprobateActivity.receiver_name,
//	    	            			OrderApprobateActivity.receiver_address,OrderApprobateActivity.leave_msg,mCouponCode);
//	    	            	alipay.alipay();
	    	            	mDialog.dismiss();
	    	            	mButton_pay.setEnabled(true);
						}
					});
			
			setShadow(true);
			mDialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim);
//			mDialog.getWindow().setBackgroundDrawableResource(R.color.vifrification);
			mDialog.show();
			
			mDialog.setOnDismissListener(new OnDismissListener() {
				
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					setShadow(false);
					mButton_pay.setEnabled(true);
				}
			});
		}
		
	}
	
	public void setShadow(Boolean isTransparent){
		WindowManager.LayoutParams lp=getWindow().getAttributes();
		if(isTransparent){
	        lp.alpha=0.3f;
	        lp.dimAmount=0.3f;
	        getWindow().setAttributes(lp);
	        getWindow().setAttributes(lp);
//	        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		}else{
			lp.alpha=1.0f;
	        lp.dimAmount=1.0f;
	        getWindow().setAttributes(lp);
	        getWindow().setAttributes(lp);
		}

	}
	
	public Boolean isNull(String str){
		if(str!=null&&!str.equals("")&&str!=""){
			return true;
		}
		return false;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			mButton_pay.setEnabled(true);
			if(ShopDetailActivity.mList.contains(this)){
				ShopDetailActivity.mList.remove(this);
			}
			this.finish();
			return true;
		}
		return false;
	}
	
	protected void showProgress() {
		this.runOnUiThread(new Runnable() {
			public void run() {	
				if(mProgress==null){
					mProgress = new ProgressDialog(ConfirmOrderActivity.this);
					mProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
					mProgress.setMessage("正在处理订单,请稍后...");
				}
				mProgress.show();
				
				
			}
		});
	}

	/**
	 * 取消等待框
	 */
	protected void hideProgress() {
		
		this.runOnUiThread(new Runnable() {
			public void run() {
				if (mProgress != null) {
					mProgress.dismiss();
				}
			}
		});
	}
}
